<?php

/**
 * Some rights reserved：abc3210.com
 * Contact email:admin@abc3210.com
 */
class Html {

    private $url, $html_root, $queue, $categorys;

    public function __construct() {
        import('@.ORG.Util.Url');
        //栏目缓存
        $this->categorys = F("Category");
        $this->url = new Url();
        //强制生成静态目录
        $this->html_root = C("HTML_ROOT");
        //站点配置
        $this->sitelist = F("Config");
        $this->Model = F("Model");
        define('HTML', true);
        C('HTML_FILE_SUFFIX', "");
    }

    /**
     * 传递this
     * @param type $thiss 
     */
    public function pointer(&$thiss) {
        $this->this = $thiss;
    }

    /**
     * 生成内容页
     * @param  $file 文件地址
     * @param  $data 数据
     * @param  $array_merge 是否合并
     * @param  $action 方法
     * @param  $upgrade 是否是升级数据
     */
    public function show($file, $data = '', $array_merge = 1, $action = 'add', $upgrade = 0) {
        $id = $data['id'];
        if ($array_merge) {
            $data = new_stripslashes($data);
            $data = array_merge($data['system'], $data['model']);
        }
        //通过rs获取原始值
        $rs = $data;
        $catid = $data['catid'];
        $CATEGORYS = $this->categorys;
        $CAT = $CATEGORYS[$catid];
        //取得栏目配置
        $CAT['setting'] = unserialize($CAT['setting']);
        //模型ID
        $this->modelid = $modelid = $CAT['modelid'];
        $this->table_name = $this->Model[$this->modelid]['tablename'];
        //处理由于通过关联模型获取数据，会把副表字段内容归入下标为 表名_data ，重现组合
        if (isset($data[ucwords($this->table_name) . "_data"])) {
            $data = array_merge($data, $data[ucwords($this->table_name) . "_data"]);
            unset($data[ucwords($this->table_name) . "_data"]);
        }

        if (isset($data['paginationtype'])) {
            $paginationtype = $data['paginationtype'];
            $maxcharperpage = $data['maxcharperpage'];
        } else {
            $paginationtype = 0;
        }

        //载入字段数据处理类
        require_once RUNTIME_PATH . 'content_output.class.php';
        $content_output = new content_output($modelid, $catid, $CATEGORYS);

        $output_data = $content_output->get($data);
        $output_data['id'] = $id;
        extract($output_data);

        $this->table_name = $this->Model[$this->modelid]['tablename'];
        $this->db = M(ucwords($this->table_name));

        //上一页
        $where = array();
        $where['status'] = array("EQ", "99");
        $where['id'] = array("LT", $id);
        $previous_page = $this->db->where($where)->order(array("id" => "DESC"))->find();
        //下一页
        $where['id'] = array("GT", $id);
        $next_page = $this->db->where($where)->find();

        if (empty($previous_page)) {
            $previous_page = array('title' => "第一页", 'thumb' => CONFIG_SITEURL . 'statics/images/nopic_small.gif', 'url' => 'javascript:alert(\'第一页\');');
        }
        if (empty($next_page)) {
            $next_page = array('title' => "最后一页", 'thumb' => CONFIG_SITEURL . 'statics/images/nopic_small.gif', 'url' => 'javascript:alert(\'最后一页\');');
        }

        $output_data['title'] = $title = strip_tags($title);
        //SEO
        $seo_keywords = '';
        if (!empty($keywords))
            $seo_keywords = implode(',', $keywords);
        $SEO = seo($catid, $title, $description, $seo_keywords);

        $ishtml = 1;
        //模板处理开始
        $template = $template ? $template : $CAT['setting']['show_template'];

        $newstempid = explode(".", $template);
        $template = $newstempid[0];
        //检测模板是否存在、不存在使用默认！
        $tempstatus = parseTemplateFile("Show:" . $template);
        if ($tempstatus == false) {
            $template = "show";
            unset($tempstatus);
        }

        //模板处理END
        //分页处理
        $pages = $titles = '';
        if ($paginationtype == 1) {
            //自动分页
            if ($maxcharperpage < 10)
                $maxcharperpage = 500;
            import('@.ORG.Util.Contentpage');
            $contentpage = new Contentpage();
            $contentfy = $contentpage->get_data($content, $maxcharperpage);
            //自动分页有时会造成返回空，如果返回空，就不分页了
            if (!empty($contentfy)) {
                $content = $contentfy;
            }
        }
        // $output_data = array_merge(array(),$output_data);
        //分配变量到模板 
        $this->this->assign($output_data);
        //seo分配到模板
        $this->this->assign("SEO", $SEO);
        //上一篇 下一篇
        $this->this->assign("previous_page", $previous_page);
        $this->this->assign("next_page", $next_page);
        //栏目ID
        $this->this->assign("catid", $catid);

        $tpAction = A("Base");
        $template = $tpAction->parseTemplateFile("Show:" . $template);
        unset($tpAction);

        if ($paginationtype != 0) {
            //手动分页
            $CONTENT_POS = strpos($content, '[page]');
            if ($CONTENT_POS !== false) {
                $contents = array_filter(explode('[page]', $content));
                $pagenumber = count($contents);
                if (strpos($content, '[/page]') !== false && ($CONTENT_POS < 7)) {
                    $pagenumber--;
                }
                for ($i = 1; $i <= $pagenumber; $i++) {
                    $pageurls[$i] = $this->url->show($id, $i, $catid, $data['inputtime'], $data['prefix'], '', 'edit');
                }
                $END_POS = strpos($content, '[/page]');
                if ($END_POS !== false) {
                    if ($CONTENT_POS > 7) {
                        $content = '[page]' . $title . '[/page]' . $content;
                    }
                    if (preg_match_all("|\[page\](.*)\[/page\]|U", $content, $m, PREG_PATTERN_ORDER)) {
                        foreach ($m[1] as $k => $v) {
                            $p = $k + 1;
                            $titles[$p]['title'] = strip_tags($v);
                            $titles[$p]['url'] = $pageurls[$p][0];
                        }
                    }
                }

                //加载url规则缓存 show_ruleid
                $urlrules = F("urlrules");
                $urlrules = explode("|", $urlrules[$CAT['show_ruleid']]);
                //URL规则处理
                $rs = explode("/", $urlrules[0]);
                $urlrules[0] = $rs[count($rs) - 1];
                $rs = explode("/", $urlrules[1]);
                $urlrules[1] = $rs[count($rs) - 1];

                $u = explode("/", $pageurls[1][0]);
                unset($u[count($u) - 1]);
                $u = implode("/", $u);
                foreach ($urlrules as $k => $r) {
                    $urlrules[$k] = $u . "/" . $r;
                }
                $urlrules = implode("~", $urlrules);
                //自定义文件名
                if ($prefix) {
                    $Filename = trim($prefix);
                } else {
                    $Filename = $id;
                }
                $urlrules = str_replace(array('{$id}'), array($Filename), $urlrules);
                define('URLRULE', $urlrules);
                $pages = "";
                //生成分页
                foreach ($pageurls as $page => $urls) {
                    //$pagenumber 分页总数
                    $_GET[C("VAR_PAGE")] = $page;
                    $pages = page($pagenumber, 1, $page, 6, C("VAR_PAGE"), '', true)->show("default");
                    //判断[page]出现的位置是否在第一位 
                    if ($CONTENT_POS < 7) {
                        $content = $contents[$page];
                    } else {
                        if ($page == 1 && !empty($titles)) {
                            $content = $title . '[/page]' . $contents[$page - 1];
                        } else {
                            $content = $contents[$page - 1];
                        }
                    }
                    if ($titles) {
                        list($title, $content) = explode('[/page]', $content);
                        $content = trim($content);
                        if (strpos($content, '</p>') === 0) {
                            $content = '<p>' . $content;
                        }
                        if (stripos($content, '<p>') === 0) {
                            $content = $content . '</p>';
                        }
                    }

                    //分页
                    $this->this->assign("pages", $pages);
                    $this->this->assign("content", $content);
                    $pagefile =  $urls[1]; //生成路径
                    $this->this->buildHtml($pagefile, SITE_PATH."/", $template);
                }
                $this->this->assign("pages", "");
                return true;
            }
        }
        $this->this->assign("content", $content);
        //分页处理结束
        $filename = $file; //生成路径
        $this->this->buildHtml($filename, SITE_PATH."/", $template);
        return true;
    }

    /**
     * 生成栏目列表
     * @param $catid 栏目id
     * @param $page 当前页数
     */
    public function category($catid, $page = 0) {
        //把分页分配到模板
        $this->this->assign(C("VAR_PAGE"), $page);
        //获取栏目数据
        $CAT = $this->categorys[$catid];
        if (empty($CAT)) {
            $this->this->error("栏目不存在");
        }
        @extract($CAT);
        //是否生成列表
        if (!$ishtml) {
            return false;
        }
        $setting = unserialize($setting);
        //SEO
        if (!$setting['meta_title']) {
            $setting['meta_title'] = $catname;
        }
        $SEO = seo($catid, $setting['meta_title'], $setting['meta_description'], $setting['meta_keywords']);
        //分页
        $page = intval($page);
        //父目录
        $parentdir = $CAT['parentdir'];
        //目录
        $catdir = $CAT['catdir'];
        //生成地址
        if ($CAT['create_to_html_root']) {
            $parentdir = '';
        }
        //生成路径
        $base_file = $this->url->get_list_url($setting['category_ruleid'], $parentdir, $catdir, $catid, $page);
        //加载url规则缓存
        $urlrules = F("urlrules");
        //取得当前栏目URL规则
        $urlrules = explode('|', $urlrules[$category_ruleid]);

        //生成路径
        $filename =  $base_file;
        //URLRULES
        foreach ($urlrules as $_k => $_v) {
            $urlrules[$_k] = '/' . $_v;
        }
        //生成类型为0的栏目
        if ($type == 0) {
            //栏目首页模板
            $template = $setting['category_template'] ? $setting['category_template'] : 'category';
            //栏目列表页模板
            $template_list = $setting['list_template'] ? $setting['list_template'] : 'list';
            //判断使用模板类型，如果有子栏目使用频道页模板，终极栏目使用的是列表模板
            $template = $child ? "Category:" . $template : "List:" . $template_list;
            $tpar = explode(".", $template);
            $template = $tpar[0];
            unset($tpar);
            $tpAction = A("Base");
            $template = $tpAction->parseTemplateFile($template);
            unset($tpAction);
            //模板检测
            if (!$template) {
                $this->this->error("模板不存在！", U("Contents/Create_html/category"));
            }
            //取得不包含文件名的URL规则路径
            $urlst = str_replace(basename($urlrules[0]), "", $urlrules[0]);
            //URL规则
            $urlrules = str_replace('{$catid}', $catid, implode('~', $urlrules));
            //用于分页生成
            define('URLRULE', str_replace($urlst, str_replace(basename($base_file), "", $base_file), $urlrules));
        }
        //分配变量到模板 
        $this->this->assign($CAT);
        //seo分配到模板
        $this->this->assign("SEO", $SEO);
        //生成
        $this->this->buildHtml($filename, SITE_PATH."/", $template);
    }

    /**
     * 更新首页
     */
    public function index($page = 1) {
        //把分页分配到模板
        $this->this->assign(C("VAR_PAGE"), $page);
        $tp = explode(".", CONFIG_INDEXTP);
        $urlrules = 'index' . CONFIG_SITEINDEXTYPE . '~index_{$page}' . CONFIG_SITEINDEXTYPE;
        //生成规则
        define('URLRULE', str_replace($urlst, str_replace(basename($base_file), "", $base_file), $urlrules));

        if ($page > 1) {
            $filename = "index_" . $page . CONFIG_SITEINDEXTYPE;
        } else {
            $filename =  "index" . CONFIG_SITEINDEXTYPE;
        }
        $tpAction = A("Base");
        $template = $tpAction->parseTemplateFile("Index:" . $tp[0]);
        unset($tpAction);
        $SEO = seo();
        //seo分配到模板
        $this->this->assign("SEO", $SEO);
        $this->this->buildHtml($filename, SITE_PATH."/", $template);
    }

    /**
     * 生成相关栏目列表、只生成前5页
     * @param $catid
     */
    public function create_relation_html($catid) {
        for ($page = 1; $page < 6; $page++) {
            $this->category($catid, $page);
        }
        //检查当前栏目的父栏目，如果存在则生成
        $arrparentid = $this->categorys[$catid]['arrparentid'];
        if ($arrparentid) {
            $arrparentid = explode(',', $arrparentid);
            foreach ($arrparentid as $catid) {
                if ($catid)
                    $this->category($catid, 1);
            }
        }
    }

    /**
     * 生成自定义页面 
     */
    public function createhtml($path, $data) {
        if (!file_exists($path) || !is_array($data)) {
            return false;
        }
        $htmlpath =  $data['tempname'];
        $this->this->buildHtml($htmlpath, SITE_PATH.$data['temppath'], $path);
        return true;
    }

}